חפש סקריפטים עבור "THE SCRIPT"
QEMA - Quadruple Moving Averages (50,100,200,300)The script combines the common moving averages 50,100 and 200 and adds an additional MA300 to the graph.
The Three EMA'sThe script is three EMA's that are fit into one indicator. Can be well used in EMA trading system for short and long term.
RSI & RVI OB/OS Alert ArrowThe script shows arrows on bars that are in overbought or oversold, based on the set parameters of Relative Strength Index ( RSI ) and Relative Volatility Index (RVI).
Also there is a universal allert, which includes both conditions - overbought and oversold.
You can change the period of RSI and RVI, as well as the upper and lower boundaries of these indicators.
Renko with custom sourceThe script allows you to set custom date source for Renko chart through Format dialog.
On Balance VolumeThe script applies an EMA to OBV . By default, the EMA=13 periods. All calculations are based off the closing price.
Williams %RThe script applies an EMA to the Williams %R. By default, the %R=21 while the EMA=13 periods. All calculations are based off the closing price.
YK Fuller BarsThe script highlights "Fuller's pins" and generates alerts when these bars are appearing
Synthetic Price Action GeneratorNOTICE:
First thing you need to know, it "DOES NOT" reflect the price of the ticker you will load it on. THIS IS NOT AN INDICATOR FOR TRADING! It's a developer tool solely generating random values that look exactly like the fractals we observe every single day. This script's generated candles are as fake as the never ending garbage news cycles we are often force fed and expected to believe by using carefully scripted narratives peddled as hypnotic truth to psychologically and emotionally influence you to the point of control by coercion and subjugation. I wanted to make the script's synthetic nature very clear using that analogy, it's dynamically artificial. Do not accidentally become disillusioned by this scripts values, make trading decisions from it, and lastly don't become victim to predatory media magic ministry parrots with pretty, handsome smiles, compelling you to board their ferris wheel of fear. Now, on to the good stuff...
BACKSTORY:
Occasionally I find myself in situations where I have to build analyzers in Pine to actually build novel quantitative analytic indicators and tools worthy of future use. These analyzers certainly don't exist on this platform, but usually are required to engineer and tweak algorithms of the highest quality with the finest computational caliber. I have numerous other synthesizers to publish besides this one.
For many reasons, I needed a synthetic environment to utilize the analyzers I built in Pine, to even pursue building some exotic indicators and algorithms. Pine doesn't allow sourcing of tuples. Not to mention, I required numerous Pine advancements to make long held dreams into tangible realities. Many Pine upgrades have arrived and MANY, MANY more are in need of implementation for all. Now that I have this, intending to use it in the future often when in need, you can now use it too. I do anticipate some skilled Pine poets will employ this intended handy utility to design and/or improved indicators for trading.
ORIGIN:
This was inspired by the brilliance from the world renowned ALGOmist John F. Ehlers, but it's taken on a completely alien form from its original DNA. Browsing on the internet for something else, I came across an article with a small code snippet, and I remembered an old wish of mine. I have long known that by flipping back and forth on specific tickers and timeframes in my Watchlist is not the most efficient way to evaluate indicators in multiple theatres of price action. I realized, I always wanted to possess and use this sort of tool, so... I put it into Pine form, but now have decided to inject it with Pine Script steroids. The outcome is highly mutable candle formations in a reusable mutagenic package, observable above and masquerading as genuine looking price candles.
OVERVIEW:
I guess you could call it a price action synthesizer, but I entitled it "Synthetic Price Action Generator" for those who may be searching for such a thing. You may find this more useful on the All or 5Y charts initially to witness indication from beginning (barstate.isfirst === barindex==0) to end (last_bar_index), but you may also use keyboard shortcuts + + to view the earliest plottable bars on any timeframe. I often use that keyboard shortcut to qualify an indicator through the entirety of it's runtime.
A lot can go wrong unexpectedly with indicator initialization, and you will never know it if you don't inspect it. Many recursively endowed Infinite Impulse Response (IIR) Filters can initialize with unintended results that minutely ring in slightly erroneous fashion for the entire runtime, beginning to end, causing deviations from "what should of been..." values with false signals. Looking closely at spg(), you will recognize that 3 EMAs are employed to manage and maintain randomness of CLOSE, HIGH, and LOW. In fact, any indicator's barindex==0 initialization can be inspected with the keyboard shortcuts above. If you see anything obviously strange in an authors indicator, please contact the developer if possible and respectfully notify them.
PURPOSE:
The primary intended application of this script, is to offer developers from advanced to even novice skill levels assistance with building next generation indicators. Mostly, it's purpose is for testing and troubleshooting indicators AND evaluating how they perform in a "manageable" randomized environment. Some times indicators flake out on rare but problematic price fluctuations, and this may help you with finding your issues/errata sooner than later. While the candles upon initial loading look pristine, by tweaking it to the minval/maxval parameters limits OR beyond with a few code modifications, you can generate unusual volatility, for instance... huge wicks. Limits of minval= and maxval= of are by default set to a comfort zone of operation. Massive wicks or candle bodies will undoubtedly affect your indication and often render them useless on tickers that exhibit that behavior, like WGMCF intraday currently.
Copy/paste boundaries are provided for relevant insertion into another script. Paste placement should happen at the very top of a script. Note that by overwriting the close, open, high, etc... values, your compiler will give you generous warnings of "variable shadowing" in abundance, but this is an expected part of applying it to your novel script, no worries. plotcandle() can be copied over too and enabled/disabled in Settings->Style. Always remember to fully remove this scripts' code and those assignments properly before actual trading use of your script occurs, AND specifically when publishing. The entirety of this provided code should never, never exist in a published indicator.
OTHER INTENTIONS:
Even though these are 100% synthetic generated price points, you will notice ALL of the fractal pseudo-patterns that commonly exist in the markets, are naturally occurring with this generator too. You can also swiftly immerse yourself in pattern recognition exercises with increased efficiency in real time by clicking any SPAG Setting in focus and then using the up/down arrow keys. I hope I explained potential uses adequately...
On a personal note, the existence of fractal symmetry often makes me wonder, do we truly live in a totality chaotic universe or is it ordered mathematically for some outcomes to a certain extent. I think both. My observations, it's a pre-deterministic reality completely influenced by infinitesimal amounts of sentient free will with unimaginable existing and emerging quantities. Some how an unknown mysterious mechanism governing the totality of universal physics and mathematics counts this 100.0% flawlessly and perpetually. Anyways, you can't change the past that long existed before your birth or even yesterday, but you can choose to dream, create, and forge the future into your desires and hopes. As always, shite always happens when your not looking for it. What you choose to do after stepping in it unintentionally... is totally up to you. :) Maybe this tool and tips provided will aid you in not stepping in an algo cachucha up to your ankles somehow.
SCRIPTING LESSONS PORTRAYED IN THIS SCRIPT:
Pine etiquette and code cleanliness
Overwrite capabilities of built-in Pine variables for testing indicators
Various techniques to organize Settings panel while providing ease of adjustment utility
Use of tooltip= to provide users adequate valuable information. Most people want to trade with indicators, not blindly make adjustments to them without any knowledge of their intended operation/effects
When available time provides itself, I will consider your inquiries, thoughts, and concepts presented below in the comments section, should you have any questions or comments regarding this indicator. When my indicators achieve more prevalent use by TV members , I may implement more ideas when they present themselves as worthy additions. Have a profitable future everyone!
Supply and DemandThis is a "Supply and Demand" script designed to help traders spot potential levels of supply (resistance) and demand (support) in the market by identifying pivot points from past price action.
Differences from Other Scripts:
Unlike many pivot point scripts, this one offers a greater degree of customization and flexibility, allowing users to determine how many ranges of pivot points they wish to plot (up to 10), as well as the number of the most recent ranges to display.
Furthermore, it allows users to restrict the plotting of pivot points to specific timeframes (15 minutes, 30 minutes, 1 hour, 4 hours, and daily) using a toggle input. This is useful for traders who wish to focus on these popular trading timeframes.
This script also uses the color.new function for a more transparent plotting, which is not commonly used in many scripts.
How to Use:
The script provides two user inputs:
"Number of Ranges to Plot (1-10)": This determines how many 10-bar ranges of pivot points the script will calculate and potentially plot.
"Number of Last Ranges to Show (1-?)": This determines how many of the most recent ranges will be displayed on the chart.
"Limit to specific timeframes?": This is a toggle switch. When turned on, the script only plots pivot points if the current timeframe is one of the following: 15 minutes, 30 minutes, 1 hour, 4 hours, or daily.
The pivot points are plotted as circles on the chart, with pivot highs in red and pivot lows in green. The transparency level of these plots can be adjusted in the script.
Market and Conditions:
This script is versatile and can be used in any market, including Forex, commodities, indices, or cryptocurrencies. It's best used in trending markets where supply and demand levels are more likely to be respected. However, like all technical analysis tools, it's not foolproof and should be used in conjunction with other indicators and analysis techniques to confirm signals and manage risk.
A technical analyst, or technician, uses chart patterns and indicators to predict future price movements. The "Supply and Demand" script in question can be an invaluable tool for a technical analyst for the following reasons:
Identifying Support and Resistance Levels : The pivot points plotted by this script can act as potential levels of support and resistance. When the price of an asset approaches these pivot points, it might bounce back (in case of support) or retreat (in case of resistance). These levels can be used to set stop-loss and take-profit points.
Timeframe Analysis : The ability to limit the plotting of pivot points to specific timeframes is useful for multiple timeframe analysis. For instance, a trader might use a longer timeframe to determine the overall trend and a shorter one to decide the optimal entry and exit points.
Customization : The user inputs provided by the script allow a technician to customize the ranges of pivot points according to their unique trading strategy. They can choose the number of ranges to plot and the number of the most recent ranges to display on the chart.
Confirmation of Other Indicators : If a pivot point coincides with a signal from another indicator (for instance, a moving average crossover or a relative strength index (RSI) divergence), it could provide further confirmation of that signal, increasing the chances of a successful trade.
Transparency in Plots : The use of the color.new function allows for more transparent plotting. This feature can prevent the chart from becoming too cluttered when multiple ranges of pivot points are plotted, making it easier for the analyst to interpret the data.
In summary, this script can be used by a technical analyst to pinpoint potential trading opportunities, validate signals from other indicators, and customize the display of pivot points to suit their individual trading style and strategy. Always remember, however, that no single indicator should be used in isolation, and effective risk management strategies should always be employed.
extended session - Regular Opening-Range- JayyOpening Range and some other scripts updated to plot correctly (see comments below.) There are three variations of the fibonacci expansion beyond the opening range and retracements within the opening range of the US Market session - I have not put in the script for the other markets yet.
The three scripts have different uses and strengths:
The extended session script (with the script here below) will plot the opening range whether you are using the extended session or the regular session. (that is to say whether "ext" in the lower right hand corner is highlighted or not.). While in the extended session the opening range has some plotting issues with periods like 13 minutes or any period that is not divisible into 330 mins with a round number outcome (eg 330/60 =5.5. Therefore an hour long opening range has problems in the extended session.
The pre session script is only for the premarket. You can select any opening range period you like. I have set the opening range to be the full premarket session. If you select a different session you will have to unselect "pre open to 9:30 EST for Opening Range?" in the format section. The script defaults to 15 minutes in the "period Of Pre Opening Range?". To go back to the 4 am to 9:30 pre opening range select "pre open to 9:30 EST for Opening Range?" there is no automatic 330 minute selection.
The past days offset script only works in 5 min or 15 minute period. It will show the opening range from up to 20 days past over the current days price action. Use this for the regular session only. 0 shows the current day's opening range. Use the positive integers for number of days back ie 1, 2, 3 etc not -1, -2, -3 etc. The script is preprogrammed to use the current day (0).
Scripts updated to plot correctly: One thing they all have in common is a way of they deal with a somewhat random problem that shifts the plots 4 hours in one direction or the other ie the plot started at 9:30 EST or 1:30PM EST. This issue started to occur approximately June 22, 2015 and impacts any script that tried to use "session" times to manage a plot in my scripts. The issue now seems to have been resolved during this past week.
Just in case the problem reoccurs I have added a "Switch session plot?" to each script. If the plot looks funny check or uncheck the "Switch session plot?" and see the difference. Of course if a new issue crops up it will likely require a different fix.
I have updated all of the scripts shown on this chart. If you are using a script of mine that suffers from the compiler issue then you will find an update on this chart. You can get any and all of the scripts by clicking on the small sideways wishbone on the left middle of the chart. You will see a dialogue box. Then click "make it mine". This will import all of the scripts to your computer and you can play around with them all to decide what you want and what you don't want. This is the easiest way to get all of the scripts in one fell swoop. It is also the easiest way for me to make all of the scripts available. I do not have all of the plots visible since it is too messy and one of the scripts (pre OR) is only for the regular session. To view the scripts click on the blue eye to the right of the script title to show it on this script. If you can only use the regular session. The scripts will all (with the exception of the pre OR) work fine.
If for any reason this script seems flakey refresh the page r try a slightly different period. I have noticed that sometimes randomly the script loves to return to the 5 min OR. This is a very new issue transient issue. As always if you see an issue please let me know.
Cheers Jayy
Options Series - Dynamic Support & Resistance
🌟 Key Features & How It Works:
⭐ Dynamic Support and Resistance Management:
The script dynamically calculates and draws support and resistance lines based on pivot highs and pivot lows. Unlike static levels that remain unchanged, these lines are updated in real-time. When a support or resistance level is breached, the corresponding line is automatically deleted, keeping the chart clean and relevant. This feature ensures that the trader is always looking at valid support and resistance levels based on the current price action.
⭐ Use of Arrays for Line Management:
The script utilizes arrays to store and manage support and resistance lines (array.new_line(0)). This is a more advanced feature of Pine Script v5, allowing for efficient handling of multiple lines on the chart. By using arrays, the script can easily track and manipulate multiple lines (adding, removing, updating), ensuring that the chart remains optimized for real-time analysis.
⭐ Customizable Inputs for Flexibility:
The script includes user inputs for the pivot length and the line width, making it adaptable to different trading styles and preferences. The pivot length determines how sensitive the indicator is to price changes, while the line width allows traders to customize the visual representation of support and resistance levels. These inputs add flexibility and make the script accessible to a broad range of traders.
⭐ Efficient Breach Detection Mechanism:
The isBreached function is a key part of the script. It checks whether the current price has breached any of the existing support or resistance levels. If a breach is detected (i.e., the price crosses below a support or above a resistance), the respective line is deleted, ensuring that only active and valid lines remain on the chart. This automatic update feature reduces the need for manual intervention, helping traders stay focused on key price levels.
⭐ Visual Clarity and Chart Cleanliness:
By deleting breached lines, the script ensures that the chart does not become cluttered with outdated or irrelevant lines. This visual clarity is crucial for traders who rely on clean, simple charts for decision-making. Removing unnecessary information helps traders make faster, more confident decisions based on the current market structure.
⭐ Scalability for Multiple Timeframes:
The use of pivot points makes the script adaptable to different timeframes, from intraday scalping to longer-term swing trading. By changing the pivot length, traders can optimize the indicator for different market environments, ensuring that it can be applied across various asset classes and timeframes.
⭐ Practical for Range-bound and Breakout Trading:
This script is particularly effective for traders who focus on range-bound markets or breakout strategies. It allows them to quickly identify areas where price is likely to reverse (support/resistance) or break out (when support/resistance is breached), providing real-time insight into market dynamics.
⭐ Simplification of Price Action Analysis:
By automating the calculation of pivots and management of support/resistance levels, the script simplifies price action analysis. Traders no longer need to manually draw or monitor these levels, which is a common task in technical analysis. This provides an edge, as it reduces the time spent on chart preparation and helps focus on executing trades.
⭐ Originality:
The script "Options Series - Pivot Based Support & Resistance" is an original approach to generating support and resistance levels using pivot points. Pivot-based techniques are popular, but the script introduces an automated dynamic way of drawing support and resistance lines, tracking breaches, and deleting lines when they are no longer valid. This aspect adds a refreshing layer of interactivity and functionality that sets it apart from basic pivot point scripts. The use of arrays to store and manage multiple support and resistance lines is also a good application of Pine Script’s newer array functionalities.
⭐ Uniqueness of the Script:
The script stands out due to its dynamic management of support and resistance lines. Unlike traditional scripts that simply plot static pivot points, this one evolves with the market by removing broken levels, ensuring only valid support and resistance lines are visible on the chart. This is particularly useful for traders who focus on clean charting. The use of arrays to store and manage the lines, alongside the efficient deletion of lines when breached, demonstrates a solid understanding of Pine Script v5's advanced features, such as array manipulation.
🚀 Conclusion:
This script stands out for its real-time adaptability, dynamic support/resistance management, and efficient use of Pine Script’s advanced features. It a powerful tool for both novice and advanced traders.
The script is an indicator designed to draw support and resistance levels based on pivot highs and lows, dynamically removing lines when they are breached. If a price crosses a support or resistance level, the respective line is deleted, ensuring the chart reflects the current state of support and resistance accurately.
WWV_LB zigzag pivot fix jayyThis is a zigzag version of LazyBear's WWV_LB. In order to plot the WWV_LB as a zigzag, it made sense to me to set the zigzag pivot at the true WWV_LB low or high pivot bars as opposed to the "pivot" bars plotted by the original WWV_LB script. The pivot point identified in the WWV_LB script is actually the point at which a wave reversal is confirmed as opposed to the true script pivot point. Confirmation of a wave reversal can, at times, lag the true pivot by a few bars especially as trendDetectionLength values increase above "1". The WWV_LB script calculates cumulative volume from wave reversal confirmation bar to wave reversal confirmation bar as opposed to the actual/true WWV_LB reversal pivot bar to reversal pivot bar. As such the waves plotted by the original and this pivot fixed scripts not only look slightly different but can also have different cumulative volumes. Confirmation of a wave reversal can lag a few bars behind the true pivot point.
The following critical lines of the original WWV_LB script determine when a wave reverses, both the true pivot and the confirmation point:mov = close>close ? 1 : close<close ? -1 : 0
trend= (mov != 0) and (mov != mov ) ? mov : nz(trend )
isTrending = rising(close, trendDetectionLength) or falling(close, trendDetectionLength)
wave=(trend != nz(wave )) and isTrending ? trend : nz(wave ) These original script lines are replicated in lines 62 to 65 of my script and are used to define wave reversal pivot bars and wave reversal confirmation bars. The original WWV_LB script does not track potential or actual pivot bars. The information can be extracted and tracked from the original script and then used to plot the actual reversal pivot bars. This allows the volume to be tracked from the actual/true pivot bars.Instead of "trendDetectionLength" I have inserted "Trend Detection Length" in the dialogue boxes. You can of course change the descriptor to what you wish by editing script line 33 to the original term or whatever you wish. You might also wish to set the default to the value "2" as per the original script. I have set the default to "3".
If you use a dark background I suggest you edit script line 4 from blackr=black to something such as blackr=yellow The volume values are shown in a vertical column of 3 numbers. Given the limitations of Pinescript Version 3 relative to V4, they are plotted at the point where the wave reversal is confirmed as opposed to the true pivot point. The zigzag lines plot the true pivot points. The plot location of numbers could be improved in Pinescript Version 4. I explain below why I have not published the Pinescript version 4 scripThe volume values plotted on the chart are calculated to be relative numbers. The script is limited to showing only three numbers vertically. Only the highest three values of a number are shown. For example, if the highest recent pip value is 12,345 only the first 3 numerals would be displayed ie 123. But suppose there is a recent value of 691. It would not be helpful to display 691 if the other wave size is shown as 123. To give the appropriate relative value the script will show a value of 7 instead of 691. This informs you of the relative magnitude of the values. This is done automatically within the script. There is likely no need to manually override the automatically calculated value. I will create a video that demonstrates the manual override method.
Should you update to Pinescript version 4? You could but if you do you will need to change the "plotchar" criteria since this script will exceed the 64 plot limit when converted to version 4. Version 4 would also allow the zigzags lines to be straight lines. However, the 50 label and line plot limit (Pinescript calls this resource sparing feature "garbage collection") significantly truncates the screen available information provided on screen. This algo optionally allows the plotting of zigzags as calculated by the original WWV_LB script. Toggling between the two script versions allows you to see the zigzag plot differences. I have also made some modifications to the original WWV_LB histogram script to adjust the pivot points.This zigzag script should be used in conjunction with the "WWV_LB pivot fix histogram jayy" shown in the panel below the main screen.
Here is a link to the original LazyBear histogram script which can be used for comparison. The differences are subtle, however, the histograms will regularly be different by a bar or two:
The lowest panel has the original LazyBear WWV_LB script for comparison. All three scripts have been set to a Trend Detection Length of 3.
jayy
Counting Stars Overlay [Market Overview Series]Hi fellow tradeurs,
So it's always been my goal to provide one of my best scripts. This is from what I call my "Market Overview" series. It is a scanner for my second best script to date. Market Overview bc of its origins as a scanner of the Kucoin Margin Coins. I realize that there are more coins that there are more margin coins that Kucoin has but I wanted to have a solid 40 coins on each coin "set". If you are unfamiliar with what I mean by 'sets' then you can view my other scanner scripts on this account for futher elaboration but to sum it up....there are 4 sets of coins I have to choose from in the settings. Each set has 40 coins in them (as there is a cap of 40 security calls that can be made per each iteration of the script on the chart). That being said...if you have the capabilities then add this script 4 times to your chart and select a diff set for each copy of the script. This has the scanner in a way that I've yet to present in my others scripts. When the alert for a coin goes off then the coins name will be printed as a label over the main chart. BTW, this was built for the 1 min timeframe and have used it EXTENSIVELY and this is the best TF for how the settings are set. I will also publish another script that will be a visual aid for this one but will rather show all the plots associated with the code that is in this scanner. Know that for the scanner it'll be best to choose a coin that has at least 1 trade/update/printed candle per minute (to be safe use BTC or ETH chart or else some of the signals will be printed if the signal arrives at a point in time where the coin on the screen does not print a candle bc no new trade or update to trades occur in TradingView. For the visual aid script that I will add right after this, there will be 20 different plots that appear. When the AVG of all of these plots is beyond the OverBought line and then the AVG line is falling for 2 bars...THEN the long signal for that coin is generated (and vise versa for short signals) Lastly regarding the visual aid script, THAT ONE will ONLY show the 20 plots that are associated with the coin that the chart is selected for. So that one is not a scanner and is just a stand alone script (again) to show whats going on in the background of this scanner. Now, once you add it however many time you want to see however many sets of coins you want, I recommend merging the scales so that they are all on one scale. I prefer mine being on the left side but all you have to do is select the 3 dots in the scripts settings in the chart window and select the scale location line and it'll open another set of lines at which point you can select "merge to scale Z" (that will be the left scale) and will put all the scales together on the left. I forgot ****If you want to see a whole diff exchange's coins you much make changes to this original script and it is further described how to do so in one of my first publications**** I REALLY hope it becomes of some benefit to you in your trading as it abundantly has in my own. It is after all one of the best of my best. Ohh, I forgot to add alerts to this but will do so immediately following this. To finish, this script DOES NOT REPAINT as far as I have EVER seen (and I have extensively searched for it bc of how good the signals were, I figured I MUST HAVE made a mistake and it did so...but alas...it does not. If you notice something on the contrary do notify me immediately with the coin, exchange, TF, and time of the occurrence and we can go from there. If anyone has any great ideas for the script then please do also let me know and if I find anyone with some abilities that mingle well with my own then lets talk as I'm always looking for good ol chaps to help me out with other scripts bc if you think this is good....well....you must imagine that I've got better that I have not/am not publishing. Aaaaaanywho, goodluck to you all. I wish you the best. ***I've got good info on how to look out for false signals but I want to see what yall come up with first before I give away all my alpha.
AND if anyone asks questions that Ive already touched on in this description or already in the comments sections then maybe someone there would be willing to waste their time answering them bc I've done quite a bit of work here that I am HAPPY to hand over to the general public but if you are not willing to do the work in reading to possibly answer your inquiries that have already been answered then I am not willing to do that work for you again. Peace and love people...peace and love. Im out.
[blackcat] L2 Ehlers Early Onset TrendLevel: 2
Background
John F. Ehlers introuced Early Onset Trend Indicator in Aug, 2014.
Function
In “The Quotient Transform” in Aug, 2014, John Ehlers described an early trend detection method, the idea of the quotient transform, that was designed to reduce the lag often found in other trend indicators. I provided a script with pine v4 code here for the early-onset trend-detection indicator and also describes an approach for creating a strategy based on this indicator as an example.
The entry points displayed in blue on the price chart are defined by the top Onset Trend Detector upper quotient crossing above a threshold value e.g zero or 0.25/-0.25 here in this script. In the article, Ehlers suggested using a different K value for the exit, so the exit points are determined by the lower Onset Trend Detector quotient crossing below a threshold e.g. zero or -0.25/0.25 here in this script.
Key Signal
Quotient1 --> upper quotient in yellow which determines long entry
Quotient2 --> lower quotient in fuchsia which determines short entry
long ---> long entry signal
short ---> short entry signal
Pros and Cons
100% John F. Ehlers definition translation, even variable names are the same. This help readers who would like to use pine to read his book.
Remarks
The 82th script for Blackcat1402 John F. Ehlers Week publication.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
Realtime 5D Profile [LucF]█ OVERVIEW
This indicator displays a realtime profile that can be configured to visualize five dimensions: volume, price, time, activity and age. For each price level in a bar or timeframe, you can display total or delta volume or ticks. The tick count measures activity on a level. The thickness of each level's line indicates its age, which helps you identify the most recent levels.
█ WARNING
The indicator only works in real time. Contrary to TradingView's line of volume profile indicators , it does not show anything on historical bars or closed markets, and it cannot display volume information if none exists for the data feed the chart is using. A realtime indicator such as this one only displays information accumulated while it is running on a chart. The information it calculates cannot be saved on charts, nor can it be recalculated from historical bars. If you refresh the chart, or the script must re-execute for some reason, as when you change inputs, the accumulated information will be lost.
Because "Realtime 5D Profile" requires time to accumulate information on the chart, it will be most useful to traders working on small timeframes who trade only one instrument and do not frequently change their chart's symbol or timeframe. Traders working on higher timeframes or constantly changing charts will be better served by TradingView's volume profiles. Before using this indicator, please see the "Limitations" section further down for other important information.
█ HOW TO USE IT
Load the indicator on an active chart (see here if you don't know how).
The default configuration displays:
• A double-sided volume profile showing at what price levels activity has occurred.
• The left side shows "down" volume, the right side shows "up" volume.
• The value corresponding to each level is displayed.
• The width of lines reflects their relative value.
• The thickness of lines reflects their age. Four thicknesses are used, with the thicker lines being the most recent.
• The total value of down/up values for the profile appears at the top.
To understand how to use profiles in your trading, please research the subject. Searches on "volume profile" or "market profile" will yield many useful results. I provide you with tools — I do not teach trading. To understand more about this indicator, read on. If you choose not to do so, please don't ask me to answer questions that are already answered here, nor to make videos; I don't.
█ CONCEPTS
Delta calculations
Volume is slotted in up or down slots depending on whether the price of each new chart update is higher or lower than the previous update's price. When price does not move between chart updates, the last known direction is used. In a perfect world, Pine scripts would have access to bid and ask levels, as this would allow us to know for sure if market orders are being filled on upticks (at the ask) or downticks (at the bid). Comparing the price of successive chart updates provides the most precise way to calculate volume delta on TradingView, but it is still a compromise. Order books are in constant movement; in some cases, order cancellations can cause sudden movements of both the bid and ask levels such that the next chart update can occur on an uptick at a lower price than the previous one (or vice versa). While this update's volume should be slotted in the up slot because a buy market order was filled, it will erroneously be slotted in the down slot because the price of the chart's update is lower than that of the previous one. Luckily, these conditions are relatively rare, so they should not adversely affect calculations.
Levels
A profile is a tool that displays information organized by price levels. You can select the maximum quantity of levels this indicator displays by using the script's "Levels" input. If the profile's height is small enough for level increments to be less than the symbol's tick size, a smaller quantity of levels is used until the profile's height grows sufficiently to allow your specified quantity of levels to be displayed. The exact position of levels is not tethered to the symbol's tick increments. Activity for one level is that which happens on either side of the level, halfway between its higher or lower levels. The lowest/highest levels in the profile thus appear higher/lower than the profile's low/high limits, which are determined by the lowest/highest points reached by price during the profile's life.
Level Values and Length
The profile's vertical structure is dynamic. As the profile's height changes with the price range, it is rebalanced and the price points of its levels may be recalculated. When this happens, past updates will be redistributed among the new profile's levels, and the level values may thus change. The new levels where updates are slotted will of course always be near past ones, but keep this fluidity in mind when watching level values evolve.
The profile's horizontal structure is also dynamic. The maximum length of level lines is controlled by the "Maximum line length" input value. This maximum length is always used for the largest level value in the profile, and the length of other levels is determined by their value relative to that maximum.
Updates vs Ticks
Strictly speaking, a tick is the record of a transaction between two parties. On TradingView, these are detected on seconds charts. On other charts, ticks are aggregated to form a chart update . I use the broader "update" term when it names both events. Note that, confusingly, tick is also used to name an instrument's minimal price increment.
Volume Quality
If you use volume, it's important to understand its nature and quality, as it varies with sectors and instruments. My Volume X-ray indicator is one way you can appraise the quality of an instrument's intraday volume.
█ FEATURES
Double-Sided Profiles
When you choose one of the first two configuration selections in the "Configuration" field's dropdown menu, you are asking the indicator to display a double-sided profile, i.e., where the down values appear on the left and the up ones on the right. In this mode, the formatting options in the top section of inputs apply to both sides of the profile.
Single-Sided Profiles
The six other selections down the "Configuration" field's dropdown menu select single-sided profiles, where one side aggregates the up/down values for either volume or ticks. In this mode, the formatting options in the top section of inputs apply to the left profile. The ones in the following "Right format" section apply to the right profile.
Calculation Mode
The "Calculation" input field allows the selection of one of two modes which applies to single-sided profiles only. Values can represent the simple total of volume or ticks at each level, or their delta. The mode has no effect when a double-sided profile is used because then, the total is represented by the sum of the left and right sides. Note that when totals are selected, all levels appear in the up color.
Age
The age of each level is always displayed as one of four line thicknesses. Thicker lines are used for the youngest levels. The age of levels is determined by averaging the times of the updates composing that level. When viewing double-sided profiles, the age of each side is calculated independently, which entails you can have a down level on the left side of the profile appear thinner than its corresponding up side level line on the right side because the updates composing the up side are more recent. When calculating the age of single-sided profiles, the age of the up/down values aggregated to calculate the side are averaged. Since they may be different, the averaged level ages will not be as responsive as when using a double-sided profile configuration, where the age of levels on each side is calculated independently and follows price action more closely. Moreover, when displaying two single-sided profiles (volume on one side and ticks on the other), the age of both sides will match because they are calculated from the same realtime updates.
Profile Resets
The profile can reset on timeframes or trend changes. The usual timeframe selections are available, including the chart's, in which case the profile will reset on each new chart bar. One of two trend detection logics can be used: Supertrend or the one used by LazyBear in his Weis Wave indicator . Settings for the trend logics are in the bottommost section of the inputs, where you can also control the display of trend changes and states. Note that the "Timeframe" field's setting also applies to the trend detection mechanism. Whatever the timeframe used for trend detection, its logic will not repaint.
Format
Formatting a profile for charts is often a challenge for traders, and this one is no exception. Varying zoom factors on your chart and the frequency of profile resets will require different profile formats. You can achieve a reasonable variety of effects by playing with the following input fields:
• "Resets on" controls how frequently new profiles are drawn. Spacing out profiles between bars can help make them more usable.
• "Levels" determines the maximum quantity of levels displayed.
• "Offset" allows you to shift the profile horizontally.
• "Profile size" affects the global size of the profile.
• Another "Size" field provides control over the size of the totals displayed above the profile.
• "Maximum line length" controls how far away from the center of the bar the lines will stretch left and right.
Colors
The color and brightness of levels and totals always allows you to determine the winning side between up and down values. On double-sided profiles, each side is always of one color, since the left side is down values and the right side, up values. However, the losing side is colored with half its brightness, so the emphasis is put on the winning side. When there is no winner, the toned-down version of each color is used for both sides. Single-sided profiles use the up and down colors in full brightness on the same side. Which one is used reflects the winning side.
Candles
The indicator can color candle bodies and borders independently. If you choose to do so, you may want to disable the chart's bars by using the eye icon near the symbol's name.
Tooltips
A tooltip showing the value of each level is available. If they do not appear when hovering over levels, select the indicator by clicking on its chart name. This should get the tooltips working.
Data Window
As usual, I provide key values in the Data Window, so you can track them. If you compare total realtime volumes for the profile and the built-in "Volume" indicator, you may see variations at some points. They are due to the different mechanisms running each program. In my experience, the values from the built-in don't always update as often as those of the profile, but they eventually catch up.
█ LIMITATIONS
• The levels do not appear exactly at the position they are calculated. They are positioned slightly lower than their actual price levels.
• Drawing a 20-level double-sided profile with totals requires 42 labels. The script will only display the last 500 labels,
so the number of levels you choose affects how many past profiles will remain visible.
• The script is quite taxing, which will sometimes make the chart's tab less responsive.
• When you first load the indicator on a chart, it will begin calculating from that moment; it will not take into account prior chart activity.
• If you let the script run long enough when using profile reset criteria that make profiles last for a long time, the script will eventually run out of memory,
as it will be tracking unmanageable amounts of chart updates. I don't know the exact quantity of updates that will cause this,
but the script can handle upwards of 60K updates per profile, which should last 1D except on the most active markets. You can follow the number of updates in the Data Window.
• The indicator's nature makes it more useful at very small timeframes, typically in the sub 15min realm.
• The Weis Wave trend detection used here has nothing to do with how David Weis detects trend changes.
LazyBear's version was a port of a port, so we are a few generations removed from the Weis technique, which uses reversals by a price unit.
I believe the version used here is useful nonetheless because it complements Supertrend rather well.
█ NOTES
The aggregated view that volume and tick profiles calculate for traders is a good example of one of the most useful things software can do for traders: look at things from a methodical, mathematical perspective, and present results in a meaningful way. Profiles are powerful because, if the volume data they use is of good enough quality, they tell us what levels are important for traders, regardless of the nature or rationality of the methods traders have used to determine those levels. Profiles don't care whether traders use the news, fundamentals, Fib numbers, pivots, or the phases of the moon to find "their" levels. They don't attempt to forecast or explain markets. They show us real stuff containing zero uncertainty, i.e., what HAS happened. I like this.
The indicator's "VPAA" chart name represents four of the five dimensions the indicator displays: volume, price, activity and age. The time dimension is implied by the fact it's a profile — and I couldn't find a proper place for a "T" in there )
I have not included alerts in the script. I may do so in the future.
For the moment, I have no plans to write a profile indicator that works on historical bars. TradingView's volume profiles already do that, and they run much faster than Pine versions could, so I don't see the point in spending efforts on a poor ersatz.
For Pine Coders
• The script uses labels that draw varying quantities of characters to break the limitation constraining other Pine plots/lines to bar boundaries.
• The code's structure was optimized for performance. When it was feasible, global arrays, "input" and other variables were used from functions,
sacrificing function readability and portability for speed. Code was also repeated in some places, to avoid the overhead of frequent function calls in high-traffic areas.
• I wrote my script using the revised recommendations in the Style Guide from the Pine v5 User Manual.
█ THANKS
• To Duyck for his function that sorts an array while keeping it in synch with another array.
The `sortTwoArrays()` function in my script is derived from the Pine Wizard 's code.
• To the one and only Maestro, RicardoSantos , the creative volcano who worked hard to write a function to produce fixed-width, figure space-padded numeric values.
A change in design made the function unnecessary in this script, but I am grateful to you nonetheless.
• To midtownskr8guy , another Pine Wizard who is also a wizard with colors. I use the colors from his Pine Color Magic and Chart Theme Simulator constantly.
• Finally, thanks to users of my earlier "Delta Volume" scripts. Comments and discussions with them encouraged me to persist in figuring out how to achieve what this indicator does.
PSv4.0 Limited Array Support Super HackThis is my "PSv4.0 Limited Array Support Super Hack", derived from MichelT's Workaround for Arrays in pine and Bubble sort script, except this utilizes line.new() to obtain one array with up to 100 indices. I provided functions that may be syntactically comparable in operation to the array class we should get with PSv5.0 when that arrives. I have no clue when that ETA shall be either, so your guess is as good as mine. Due to the complexity of the script, I would ONLY recommend this script's functions for reuse by advanced Pine programmers, not newcomers to Pine Script.
Notice: FYI, support for these functions will be limited to only errata with the included functions. Honestly, I don't have an abundance of time on a daily basis to assist members with incorporation into their newly developed scripts. I hope you will understand.
The intention of this script is to provide Pine developers with one large array having up to 100 indices until we have full native array support in the future. Availability of full use of the array is only obtained when bar_index is indicesCount-1, so bear that in mind. This script is so computationally expensive, I would only advise using it "as is" on 5Y and All Charts at it's current initial release. On smaller sampling rates such as 1D, 5D and 1M... it has a tendency to encounter runtime errors such as this message: "Calculation timed out. Remove the indicator and reapply it to the chart". I just switch to a larger sampling interval - 5Y or All. I believe this is occurring due mostly to prng() generating thousands of random floating point numbers, PLUS the overhead of using line.new() for something it wasn't originally intended for. It does also use 64 plots in full color, maxing out the plotting capabilities of Pine as well. With usage of the array functions alone in your code, I anticipate those scripts to be more server friendly.
Basically this scripts functionality, as is, generates 32 pseudorandom numbers per bar in a sky blue birds nest of random numbers. It then sorts them numerically and plots them once again in a visually stunning rainbow spectrum. You will notice the plot()s colors will invert when the sorting order is changed in Settings. I commented out a lot of plot()s because we are limited to a maximum of 64 plot()s. By commenting and uncommenting with highlighted text blocks and + , you may alter the scripts appearance when done properly.
Overall, I hope you find it useful with incorporating expected array functionality that will perpetuate the novel development of next generation indicators in Pine Script version 4.0 . Once again, check out MichelT's brilliantly crafted script mentioned above. You may be able to use both scripts incorporated into an all-in-one to have dual array support, BUT I have not tested this yet, be forewarned. I hope the community contribution of this script in open source is of some benefit to those who can utilize it properly. As always, I have included advanced Pine programming techniques that conform to proper "Pine Etiquette", so this script is more than just a complex array provision...
The comments section below is solely just for commenting and other remarks, ideas, compliments, etc... regarding only this indicator, not others. When available time provides itself, I will consider your inquiries, thoughts, and concepts presented below in the comments section, should you have any questions or comments regarding this indicator. When my indicators achieve more prevalent use by TV members, I may implement more ideas when they present themselves as worthy additions. As always, "Like" it if you simply just like it with a proper thumbs up, and also return to my scripts list occasionally for additional postings. Have a profitable future everyone!
[blackcat] L2 Ehlers Empirical Mode TraderCircumstance Remarks: Because of my carelessness, the script of the same name that I posted before was banned and hidden because the description contained content that violated the TradingView House Rule. After communicating with the MOD, I corrected the description and obtained permission to publish it again. I hereby declare. Sorry for the inconvenience!
Level: 2
Background
John F. Ehlers introuced Empirical Mode Trader Indicator in Mar, 2010.
Function
In his article “Empirical Mode Decomposition,” John Ehlers and Ric Way suggest using methods based on bandpass filtering to distinguish trending from cycling markets. The article’s trading suggestions were used to create the Empirical Mode strategy given here for pine v4 script. If the strategy determines that the marke is in trending mode, then the strategy is allowed to trade with the trend — either long, in uptrends, or short, in downtrends. If the indicator determines that the market is in cycling mode, then the strategy allows trading cycle extremes, using Bollinger bands to trigger entries. You can do this by Choosing either cycle or trend mode at inputs.
Key Signal
Trend ---> Trend signal
FracAvgPeak ---> Upper band signal
FracAvgValley ---> Lower band signal
Pros and Cons
100% John F. Ehlers definition translation, even variable names are the same. This help readers who would like to use pine to read his book.
Remarks
The 75th script for Blackcat1402 John F. Ehlers Week publication.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
[blackcat] L2 Ehlers Sine Wave Coupled Eight Planetary CycleLevel: 2
Background
Have you considered that factors outside the Earth will be related to macro market trends? Let’s discuss the relationship between the planetary movement in the Galaxy and the market movement on Earth today! Although I said that, you may have laughed out in front of the screen, but the calculations in this script are entirely based on astronomical data and mathematical relationships.
Your next question may be why you compare the movements of the eight planets and the laws of the market on the earth together? My answer comes from a Cybernetic Sine Wave indicator proposed by Dr. John F. Ehlers.
Function
L2 Ehlers Sine Wave Coupled Eight Planetary Cycle first converts the astronomical data of the eight major planets into planetary aspects/phases through mathematical relationships. Planetary aspects/phases can provide the historical and current relative positions of each planet in the mathematical triangle relationship. We can use a simple mathematical sine formula to constrain the planet's trajectory between -1 and 1, which is what we often call a sine wave.
The relationship between the sine wave and the market can be extracted from the theory of John F. Ehlers. In Ehlers' theory, market price can be modeled by the trend and cycle modes. And in his works, there are many indicators of how to completely remove the trend in the market price and only leave the cycle mode data. The Cybernetic Sine Wave indicator is exactly the cycle mode data after the market trend is stripped, and expressed in the form of a sine wave.
If you can read to here with patience, you must also be aware of the premise that the trajectories of the eight planets and the laws of the earth market can be coupled: the trajectory of the sine wave mode. Therefore, this indicator is a tool for comparing and analyzing the two in the same chart. I hope you like it.
Finally, in order to benchmark the trajectories of the eight planets and the specific market on the earth, a starting point in time is particularly important. This is the base date of the market index to be analyzed. It is the year, month, and day data specified by the index, which needs to be input by the user when analyzing a specific stock index. For example, the base date of the S&P 500 index is January 3, 1928. This date needs to be entered into the indicator to analyze the SPX500.
Key Signal
Mercury_trail ---> smoothed Mercury orbit sine wave
Venus_trail ---> smoothed Venus orbit sine wave
Earth_trail ---> smoothed Earth orbit sine wave
Earth_mirror ---> smoothed Earth mirrored orbit sine wave
Mars_trail ---> smoothed Mars orbit sine wave
Jupiter_trail ---> smoothed Jupiter orbit sine wave
Saturn_trail ---> smoothed Saturn orbit sine wave
Uranus_trail ---> smoothed Uranus orbit sine wave
Neptune_trail ---> smoothed Neptune orbit sine wave
Aspect 0, 45, 90, 225, 270 deg ---> key planet aspects
ehlersine ---> Ehlers Cybernetic Sine Wave
ehlerslsine ---> Ehlers Cybernetic Lead Sine Wave
Pros and Cons
This is a technical indicator that I have come up with on a whim, and the laws of planetary operation and the operation of the Earth market are still being explored. Hope that interested friends will share your new discoveries.
Remarks
To celebrate I released the 50th technical indicator script on TV!
Courtesy of @sal157011 John Ehlers "Cybernetic Sine Wave" indicator, I converted it from pine v2 to pine v4 in this script.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
L1 Moving Average Fingerprint for Long EntryLevel: 1
Background
This script combines moving average processing with highest high and lowest low to disclose the "fingerprint" of a specific trading pair to describe its unique behavior.
Function
Moving Average Fingerprint for Long Entry is a Level 1 pine script. It utilize several moving average of inherent highest high and lowest low and combine them with customized fingerprint coefficients to depict the unique behavior of a specific trading pair across multiple markets for long entry point identification.
Key Signal
FingerPrint1~6 are basic-level fingerprints with moving average of highest high and lowest low.
FingerPrint7~8 are composite fingerprint definitions with coefficients/weights,where coefficients/weights need to be tuned to discover the inherent "fingerprint" of a specific trading pair.
FingerPrint10~12 are composite fingerprint calculation for long entry alerts
ReadytoLong is a long entry filter where long entry point may happen within it. By using crossover() function to a customized threshold value, you can define accurate long entries.
Pros and Cons
Pros:
1. Combine moving average and extreme points to disclose a trading pair behavior.
2. Smart to tune specific set of parameters to obtain unique fingerprints of trading pairs.
3. Smart position sizing scheme by adjusting the threshold values.
Cons:
1. Require tune input parameters for each trading pair in a specific period and time frame.
2. Only long entry was studied, no short entry and re-entry are available yet to form as a trading system.
3. "ReadytoLong" is an inaccurate range where multiple long entries may happen at improper points in chop market.
4. Complex input parameters to obtain a unique fingerprint set.
Remarks
Although I wrote pine script for more than two years, this is the first script published in the community. I will publish more with my works in this platform.
Hope the community can improve this concept and make it as a trading system.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
Using `varip` variables [PineCoders]█ OVERVIEW
The new varip keyword in Pine can be used to declare variables that escape the rollback process, which is explained in the Pine User Manual's page on the execution model . This publication explains how Pine coders can use variables declared with varip to implement logic that was impossible to code in Pine before, such as timing events during the realtime bar, or keeping track of sequences of events that occur during successive realtime updates. We present code that allows you to calculate for how much time a given condition is true during a realtime bar, and show how this can be used to generate alerts.
█ WARNINGS
1. varip is an advanced feature which should only be used by coders already familiar with Pine's execution model and bar states .
2. Because varip only affects the behavior of your code in the realtime bar, it follows that backtest results on strategies built using logic based on varip will be meaningless,
as varip behavior cannot be simulated on historical bars. This also entails that plots on historical bars will not be able to reproduce the script's behavior in realtime.
3. Authors publishing scripts that behave differently in realtime and on historical bars should imperatively explain this to traders.
█ CONCEPTS
Escaping the rollback process
Whereas scripts only execute once at the close of historical bars, when a script is running in realtime, it executes every time the chart's feed detects a price or volume update. At every realtime update, Pine's runtime normally resets the values of a script's variables to their last committed value, i.e., the value they held when the previous bar closed. This is generally handy, as each realtime script execution starts from a known state, which simplifies script logic.
Sometimes, however, script logic requires code to be able to save states between different executions in the realtime bar. Declaring variables with varip now makes that possible. The "ip" in varip stands for "intrabar persist".
Let's look at the following code, which does not use varip :
//@version=4
study("")
int updateNo = na
if barstate.isnew
updateNo := 1
else
updateNo := updateNo + 1
plot(updateNo, style = plot.style_circles)
On historical bars, barstate.isnew is always true, so the plot shows a value of "1". On realtime bars, barstate.isnew is only true when the script first executes on the bar's opening. The plot will then briefly display "1" until subsequent executions occur. On the next executions during the realtime bar, the second branch of the if statement is executed because barstate.isnew is no longer true. Since `updateNo` is initialized to `na` at each execution, the `updateNo + 1` expression yields `na`, so nothing is plotted on further realtime executions of the script.
If we now use varip to declare the `updateNo` variable, the script behaves very differently:
//@version=4
study("")
varip int updateNo = na
if barstate.isnew
updateNo := 1
else
updateNo := updateNo + 1
plot(updateNo, style = plot.style_circles)
The difference now is that `updateNo` tracks the number of realtime updates that occur on each realtime bar. This can happen because the varip declaration allows the value of `updateNo` to be preserved between realtime updates; it is no longer rolled back at each realtime execution of the script. The test on barstate.isnew allows us to reset the update count when a new realtime bar comes in.
█ OUR SCRIPT
Let's move on to our script. It has three parts:
— Part 1 demonstrates how to generate alerts on timed conditions.
— Part 2 calculates the average of realtime update prices using a varip array.
— Part 3 presents a function to calculate the up/down/neutral volume by looking at price and volume variations between realtime bar updates.
Something we could not do in Pine before varip was to time the duration for which a condition is continuously true in the realtime bar. This was not possible because we could not save the beginning time of the first occurrence of the true condition.
One use case for this is a strategy where the system modeler wants to exit before the end of the realtime bar, but only if the exit condition occurs for a specific amount of time. One can thus design a strategy running on a 1H timeframe but able to exit if the exit condition persists for 15 minutes, for example. REMINDER: Using such logic in strategies will make backtesting their complete logic impossible, and backtest results useless, as historical behavior will not match the strategy's behavior in realtime, just as using `calc_on_every_tick = true` will do. Using `calc_on_every_tick = true` is necessary, by the way, when using varip in a strategy, as you want the strategy to run like a study in realtime, i.e., executing on each price or volume update.
Our script presents an `f_secondsSince(_cond, _resetCond)` function to calculate the time for which a condition is continuously true during, or even across multiple realtime bars. It only works in realtime. The abundant comments in the script hopefully provide enough information to understand the details of what it's doing. If you have questions, feel free to ask in the Comments section.
Features
The script's inputs allow you to:
• Specify the number of seconds the tested conditions must last before an alert is triggered (the default is 20 seconds).
• Determine if you want the duration to reset on new realtime bars.
• Require the direction of alerts (up or down) to alternate, which minimizes the number of alerts the script generates.
The inputs showcase the new `tooltip` parameter, which allows additional information to be displayed for each input by hovering over the "i" icon next to it.
The script only displays useful information on realtime bars. This information includes:
• The MA against which the current price is compared to determine the bull or bear conditions.
• A dash which prints on the chart when the bull or bear condition is true.
• An up or down triangle that prints when an alert is generated. The triangle will only appear on the update where the alert is triggered,
and unless that happens to be on the last execution of the realtime bar, it will not persist on the chart.
• The log of all triggered alerts to the right of the realtime bar.
• A gray square on top of the elapsed realtime bars where one or more alerts were generated. The square's tooltip displays the alert log for that bar.
• A yellow dot corresponding to the average price of all realtime bar updates, which is calculated using a varip array in "Part 2" of the script.
• Various key values in the Data Window for each parts of the script.
Note that the directional volume information calculated in Part 3 of the script is not plotted on the chart—only in the Data Window.
Using the script
You can try running the script on an open market with a 30sec timeframe. Because the default settings reset the duration on new realtime bars and require a 20 second delay, a reasonable amount of alerts will trigger.
Creating an alert on the script
You can create a script alert on the script. Keep in mind that when you create an alert from this script, the duration calculated by the instance of the script running the alert will not necessarily match that of the instance running on your chart, as both started their calculations at different times. Note that we use alert.freq_all in our alert() calls, so that alerts will trigger on all instances where the associated condition is met. If your alert is being paused because it reaches the maximum of 15 triggers in 3 minutes, you can configure the script's inputs so that up/down alerts must alternate. Also keep in mind that alerts run a distinct instance of your script on different servers, so discrepancies between the behavior of scripts running on charts and alerts can occur, especially if they trigger very often.
Challenges
Events detected in realtime using variables declared with varip can be transient and not leave visible traces at the close of the realtime bar, as is the case with our script, which can trigger multiple alerts during the same realtime bar, when the script's inputs allow for this. In such cases, elapsed realtime bars will be of no use in detecting past realtime bar events unless dedicated code is used to save traces of events, as we do with our alert log in this script, which we display as a tooltip on elapsed realtime bars.
█ NOTES
Realtime updates
We have no control over when realtime updates occur. A realtime bar can open, and then no realtime updates can occur until the open of the next realtime bar. The time between updates can vary considerably.
Past values
There is no mechanism to refer to past values of a varip variable across realtime executions in the same bar. Using the history-referencing operator will, as usual, return the variable's committed value on previous bars. If you want to preserve past values of a varip variable, they must be saved in other variables or in an array .
Resetting variables
Because varip variables not only preserve their values across realtime updates, but also across bars, you will typically need to plan conditions that will at some point reset their values to a known state. Testing on barstate.isnew , as we do, is a good way to achieve that.
Repainting
The fact that a script uses varip does not make it necessarily repainting. A script could conceivably use varip to calculate values saved when the realtime bar closes, and then use confirmed values of those calculations from the previous bar to trigger alerts or display plots, avoiding repaint.
timenow resolution
Although the variable is expressed in milliseconds it has an actual resolution of seconds, so it only increments in multiples of 1000 milliseconds.
Warn script users
When using varip to implement logic that cannot be replicated on historical bars, it's really important to explain this to traders in published script descriptions, even if you publish open-source. Remember that most TradingViewers do not know Pine.
New Pine features used in this script
This script uses three new Pine features:
• varip
• The `tooltip` parameter in input() .
• The new += assignment operator. See these also: -= , *= , /= and %= .
Example scripts
These are other scripts by PineCoders that use varip :
• Tick Delta Volume , by RicadoSantos .
• Tick Chart and Volume Info from Lower Time Frames by LonesomeTheBlue .
Thanks
Thanks to the PineCoders who helped improve this publication—especially to bmistiaen .
Look first. Then leap.
[blackcat] L2 Price Envelope TrackerLevel: 2
Background
Price envelopes sare shown at a set percentage above and below a moving average. They are used to indicate overbought and oversold levels and can be traded individually or in conjunction with a momentum indicator.
Function
L2 Price Envelope Tracker is an innovative indicator that use customized envelope of price to disclose overbought and oversold periods. With this function, long and short entries can be further developped in this pine script.
Key Signal
sma5 --> typical price moving average line
resistance --> upper envelope as resistance line
support ---> lower envelope as support line
Pros and Cons
Pros:
1. easy observe overbought and oversold zone
2. disclose exact long and short entries in overbought and oversold zones
Cons:
1. Only applicable for the trading pairs that support financial() functions. crypto/xau/xag/indice are not applicable
2. Need to tune r1 and s1 for different trading pairs
Remarks
NA
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.